<template>
  <!-- 选择人员 -->
  <el-dialog title="选择人员" min-width="670px" :before-close="handlePersonnelClose" :visible.sync="dialogPersonnelVisible"
    custom-class="el-dialog-flex" class="peopleDialogSelect" :close-on-click-modal="false" :close-on-press-escape="false"
    @open="openSelectPersonnel">
    <el-tabs v-model="activeName" @tab-click="handleTabsClick" class='el-box-column secondTab'>
      <el-tab-pane label="上级协助人" name="first" v-if='(dialogModalTitle=="责任人"&&schedulePersonTab!=undefined)||(dialogModalTitle=="责任人"&&schedulePersonTab!=null)'>
        <el-radio-group @change='personChangeTab' v-model='personName' ref="personChangeName">
          <el-radio v-for="item in schedulePersonData" :label="item" :key="item.personUserId" border>{{item.personName}}</el-radio>
        </el-radio-group>
      </el-tab-pane>
      <el-tab-pane label="选择人员" name="second" class='el-box-column el-flex'>
        <el-container>
          <el-aside style="width: 360px;" class='el-box-column el-flex'>
            <!-- 头部操作按钮 -->
            <el-card class='el-box-column el-flex secondTreeCard'>
              <div slot="header" class="clearfix">
                <el-input v-model="searchValue" placeholder="请输入人员名称" suffix-icon="el-icon-search" clearable @input="searchValueEvent"></el-input>
              </div>
              <div class="text item el-flex" v-show="treeShow">
                <el-tree :data="employeesTree" v-show="searchValue" default-expand-all :highlight-current="true"
                  :default-expanded-keys="treeExpandedKey" :filter-node-method="filterNode" ref="tree" node-key="orgId"
                  :props="defaultProps" @node-click="handleNodeClick"></el-tree>
                <el-tree v-show="searchValue==''" :highlight-current="true" :default-expanded-keys="treeExpandedKey"
                  :filter-node-method="filterNode" ref="tree" node-key="orgId" :props="defaultProps" :load="loadMailNode"
                  @node-click="handleNodeClick" :key="keyTree" lazy>
                </el-tree>
              </div>
              <div class="text item" v-show="peopleShow">
                <ul class="text mid-panels">
                  <li class="el-box panel" v-for="(val, index) in employeesPeople" :key="index" @click="choosePelple(val)">
                    <div class="user-avatar">{{val.empName}}</div>
                    <div class="listRightPart">
                      <span class="name">{{val.empName}}/{{val.empCode}}</span>
                      <span class="dept">{{val.positionStr}}</span>
                    </div>
                  </li>
                </ul>
              </div>
            </el-card>
          </el-aside>
          <el-main class="rightSection">
            <div>
              <div class="count">
                <span>已选择 ({{employeesData.length}})</span>
                <el-button type="text" style="float: right;" @click="removeAll">清除</el-button>
              </div>
              <ul class="mid-panel">
                <li class="el-box" v-for="(val, index) in employeesData" :key="index">
                  <div class="user-avatar">{{val.empName}}</div>
                  <div class="listRightPart">
                    <span class="name">{{val.empName}} <i :class="val.gender == '男'? man:woman"></i></span>
                    <span class="dept">员工编号:{{val.empCode}}</span>
                    <span class="dept" v-for="(v, i) in val.positions" :key="i">{{v.posiName}}</span>
                  </div>
                  <i class="el-icon-minus" @click="removeClick(index)"></i>
                </li>
              </ul>
            </div>
          </el-main>
        </el-container>
      </el-tab-pane>
    </el-tabs>
    <span slot="footer" class="dialog-footer" style="text-align:right;width:100%;display:inline-block;margin-top:10px;">
      <el-button type="primary" @click="handleClick(true)">确定 <i class="el-icon-document-checked el-icon--right"></i></el-button>
      <el-button @click="handleClick(false)">取消 <i class="el-icon-refresh-left"></i></el-button>
    </span>
  </el-dialog>
</template>
<script>
  import {
    Tree,
    Dialog,
    Table,
    TableColumn,
    Pagination,
    MessageBox,
    Message,
    Tabs,
    TabPane,
    Calendar,
    Upload,
    Drawer,
    Divider,
    Tag,
  } from 'element-ui'
  import {
    orgEmployeeSearch,
    orgOrganizationRoot,
    orgOrganizationParent,
    orgOrgEmpOrg
  } from '@/api/components/selectPersonnel/selectPersonnel.js'
  export default {
    props: ['dialogPersonnelVisible', 'schedulePersonList', 'multiple', 'schedulePersonData', 'dialogModalTitle',
      "schedulePersonTab"
    ],
    components: {
      'el-tree': Tree, // 树形菜单
      'el-dialog': Dialog, // 对话框
      'el-table': Table, // 表格
      'el-table-column': TableColumn, // 表格列
      'el-pagination': Pagination, // 分页
      'el-tabs': Tabs, // 标签
      'el-tab-pane': TabPane, // 标签页
      'el-calendar': Calendar, // 日历
      'el-upload': Upload, // 上传附件
      'el-drawer': Drawer, // 抽屉弹框
      'el-divider': Divider,
      'el-tag': Tag
    },
    data() {
      return {
        personChange: [],
        activeName: 'first',
        personUserName: '',
        empName: '',
        personName: '',
        searchValue: '', // 树结构上的搜索
        defaultProps: {
          label: 'orgName',
          isLeaf: 'leaf'
        },
        keyTree: 1,
        employeesTree: [], // 树形结构搜索得到数据
        orgId: "", // 树结构数据id
        treeExpandedKey: [],
        employeesData: [], // 选中人员
        man: 'el-icon-male',
        woman: 'el-icon-female',
        treeShow: true, // 隐藏树数据
        peopleShow: false, // 隐藏人员数据
        employeesPeople: [], // 得到人的列表
        treeStatus: '' // 判断树是否已经初始化
      }
    },
    updated() {
      if (this.schedulePersonTab == null) {
        this.activeName = 'second'
      }
    },
    methods: {
      searchValueEvent(val) { //树搜索
        if (val) {
          this.employees = false
          this.employeesInfo = false
          this.treeShow = false
          this.peopleShow = true
          orgEmployeeSearch({
            empName: val
          }).then(res => {
            this.employeesPeople = res.data.data.records
            this.employeesPeople.forEach(v => {
              v.personUserId = v.userId
            })
          })
        } else {
          this.searchValue = ""
          this.treeShow = true
          this.peopleShow = false
          this.keyTree += 1
        }
      },
      openSelectPersonnel() {
        if (this.treeStatus != '') {
          this.keyTree += 1
        }
        if (this.schedulePersonList == undefined || this.schedulePersonList.length == 0) {
          this.employeesData = []
          return
        } else {
          this.employeesData = JSON.parse(JSON.stringify(this.schedulePersonList))
          employeesData.forEach(e => {
            if (!e.empName) {
              e.empName = e.personName
            } else if (!e.orgName) {
              e.orgName = e.personName
            }
            if (!e.userId) {
              e.userId = e.personUserId
            }
          })
        }
      },
      // 获取数据
      loadMailNode(node, resolve) {
        this.treeStatus = "inited";
        if (node.level === 0) {
          orgOrganizationRoot().then(res => {
            let partentData = res.data.data
            resolve(partentData)
            this.orgId = partentData[0].orgId
            this.$refs.tree.setCurrentKey(this.orgId)
            this.treeExpandedKey = [this.orgId]
          }).catch(res => {
            resolve([])
          })
        } else if (node.data.isLeaf == "n" || node.data.isLeaf == "y") {
          let id = node.data.orgId
          this.orgId = id
          Promise.all([
            orgOrganizationParent(id),
            orgOrgEmpOrg(id, {
              params: {
                page: 1,
                size: 10000
              }
            })
          ]).then(([res_1, res_2]) => {
            let childDatas = res_1.data.data.records
            let personnelDatas = res_2.data.data.records
            personnelDatas.forEach(e => {
              e.leaf = true
              e.orgId = e.empId
              e.orgName = e.empName
              e.personName = e.empName
              e.personUserId = e.userId
            })
            let resultData = childDatas.concat(personnelDatas)
            resolve(resultData)
          }).catch(res => {
            resolve([])
          })
        } else {
          resolve([])
        }
      },
      // 递归遍历树形数据源
      deepChild(val) {
        let $this = this
        if (val && Array.isArray(val) && val.length) {
          val.forEach(item => {
            if (typeof item === 'object') {
              item.orgId = item.id
              item.orgName = item.name
              $this.deepChild(item.children)
            }
          })
        }
      },
      filterNode(value, data) { // 树状图
        if (!value) return true
        return data.orgName.indexOf(value) !== -1
      },
      // 点击树事件
      handleNodeClick(node) {
        if (!node.isLeaf) { // 点击单个
          let nowDatas = node
          if (this.multiple) { // 是多选
            let empCodes = this.employeesData.find((v) => v.empCode == nowDatas.empCode)
            if (empCodes) {
              Message({
                type: 'warning',
                message: '人员已存在'
              });
              return
            } else {
              this.employeesData.push(nowDatas)
            }
          } else this.employeesData = [nowDatas] // 单选
        }
      },
      // 搜索人员点击事件
      choosePelple(data) {
        let nowDatas = data
        if (this.multiple) { // 是多选
          let empCodes = this.employeesData.find((v) => v.empCode == nowDatas.empCode)
          if (empCodes) {
            return
          } else {
            this.employeesData.push(nowDatas)
          }
        } else {
          this.employeesData = [nowDatas]
        } // 单选
      },
      // 关闭选择人员按钮触发事件
      handlePersonnelClose() {
        this.$emit('dialogEmployeesData')
      },
      personChangeTab(value) { //上级协助人标签选择
        value.empName = value.personName
        value.userId = value.personUserId
        this.personChange.push(value)
        if (this.personChange.length > 1) {
          this.personChange.shift()
        }
      },
      // 点击选择人员弹框确定/取消事件
      handleClick(result) {
        if (!result) {
          return this.handlePersonnelClose()
        }
        if (this.activeName == 'first') {
          this.$emit('dialogEmployeesData', this.personChange)
        } else {
          this.$emit('dialogEmployeesData', this.employeesData)
        }
      },
      // 清除所有选中员工
      removeAll() {
        this.employeesData = []
      },
      // 移除单个选中人员事件
      removeClick(index) {
        this.employeesData.splice(index, 1)
      },
      handleTabsClick(tab) {
        this.removeAll()
        this.personName = ''
        this.personChange = []
        this.employeesData = []
      }
    }
  }
</script>
<style lang="scss" scope>
  .peopleDialogSelect {
    .el-dialog__header {
      display: none
    }

    .el-dialog__body {
      padding: 10px;
    }
  }

  .rightSection {
    padding: 0 0 10px 10px;

    .count {
      background: #fafafa;
      padding: 0 15px;
      height: 32px;
      line-height: 32px;
    }

    .mid-panel {
      margin-top: 10px;
      height: 100%;


      li {
        padding: 10px 12px 10px 20px;
        font-size: 12px;
        color: #333333;
        position: relative;

        .user-avatar {
          width: 40px;
          height: 40px;
          text-align: center;
          line-height: 40px;
          border-radius: 50%;
          color: #ffffff;
          background-color: #81C684;
        }

        .listRightPart {
          display: inline-block;
          padding-left: 10px;
          vertical-align: middle;

          .name {
            display: block;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            font-size: 14px;
            color: #333333;

            .el-icon-male {
              color: #409EFF;
            }

            .el-icon-female {
              color: pink
            }
          }

          .dept {
            display: block;
            font-size: 12px;
            color: #9e9e9e;
          }
        }

        .el-icon-minus {
          position: absolute;
          right: 10px;
          top: 28px;
          color: #9e9e9e;
          display: none;
        }

        &:hover {
          cursor: pointer;
          background-color: #f7f7f7;

          .el-icon-minus {
            display: block;
          }
        }
      }
    }
  }

  .mid-panels {
    li {
      padding: 15px 10px 7px;
      font-size: 12px;
      color: #333333;

      .user-avatar {
        width: 40px;
        height: 40px;
        text-align: center;
        line-height: 40px;
        border-radius: 50%;
        color: #ffffff;
        background-color: #81C684;
      }

      .listRightPart {
        display: inline-block;
        padding-left: 10px;
        vertical-align: middle;

        .name {
          display: block;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          font-size: 12px;
          color: #333333;
        }

        .dept {
          font-size: 12px;
          color: #9e9e9e;
        }
      }

      &:hover {
        cursor: pointer;
        background-color: #f7f7f7;
      }
    }

    .activePsn {
      background-color: #f7f7f7;
    }

    .loading {
      height: 20px;
      line-height: 20px;
      padding: 0 0 15px 100px;
    }
  }

  .secondTab {
    .el-tabs__content {
      display: flex !important;
    }

  }

  .secondTreeCard {
    .el-card__body {
      overflow: auto;
    }
  }

  .TabDialogFooter {
    padding: 10px
  }
</style>
